package ks.client.controllers.requests;

import java.net.URL;
import javax.swing.ImageIcon;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ks.client.UserContext;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.icon.IconManager;

/**
 * Controller to process ICONS requests from the server that contains the full
 * set of known icons.
 * <p>
 *
 * @author Jennifer Hunt
 * @author heineman
 */
public class IconsController implements IProcessMessage {
	
	/** In case we need to process something. */
	Lobby lobby;
	
	/** Construct controller with lobby. */
	public IconsController(Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Client has received ICONS message. Process it.
	 * 
	 * <icons>
     *    <icon name="blue_dragon"/>
     *    <icon name="red_dragon"/>
     * </icons>
     * 
	 * @param m
	 * @return
	 */
	public boolean process(Message m) {
		// Get our context
		UserContext context = lobby.getUserContext();
		
		// clear away our existing set
		IconManager im = context.getIconManager();
		im.removeAll();
		
		// extract information from the message
		Node icons = m.contents();
		
		// Find all children that are icon
		NodeList children = icons.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node n = children.item(i);
			if (n.getNodeName().equals("icon")) {
				NamedNodeMap nnp = n.getAttributes();
				Node iconNode = nnp.getNamedItem("name");
				Node uriNode = nnp.getNamedItem("uri");
				
				String iconName = iconNode.getNodeValue();
				URL uriLocation;
				try {
					uriLocation = new URL(uriNode.getNodeValue());
				} catch (Exception e) {
					e.printStackTrace();
					System.err.println("Unable to interpret url for icon:" + iconName);
					return false;
				} 
				
				// fine. Add it to the manager.
				im.add(iconName, uriLocation);
			}
		}
		
		return true;
	}
	
}

